package com.lagou.rpc.consumer.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
@Slf4j
public class ZookeeperClient {
    private static String connectString = "192.168.200.20:2181";
    private static int sessionTimeout = 60000;
    private static List<String> serverlist = new ArrayList();
    private ZooKeeper zk = null;

    public ZooKeeper getZk() {
        return zk;
    }

    // 创建到zk的客户端连接
    public void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                // 再次获取所有服务器
                try {
                    getServerList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 获取服务器列表信息
    public void getServerList() throws Exception {
        // 1获取服务器子节点信息，并且对父节点进行监听

        serverlist = zk.getChildren("/lg-rpc-provider", true);
        // 2存储服务器信息列表

        // 4打印服务器列表信息
        System.out.println(serverlist);
    }

    // 业务功能
    public void business() throws Exception {
        System.out.println("客户正在运行家 ...");
        System.in.read();
    }

    public String getFastServer(ZookeeperClient zookeeperClient) throws KeeperException, InterruptedException, IOException {
        TreeMap<String, Integer> fast = new TreeMap<>();
        for (String server : serverlist) {
            byte[] data = zookeeperClient.getZk().getData("/lg-rpc-provider/" + server, false, new Stat());
            String date = new String(data);
            int executeTime = Integer.valueOf(date) == null ? 0 : Integer.valueOf(date);
            fast.put(server, executeTime);
        }
        String minServer = null;
        for (String tem : fast.keySet()) {
            if (minServer == null) {
                minServer = tem;
            }
            if (fast.getOrDefault(tem, 0).compareTo(fast.getOrDefault(minServer, 0)) <= 0) {
                minServer = tem;
            }
        }
        return minServer;
    }
}
